import axios from "axios";
import router from "@/router"; //没权限则跳转到登录页面
import { ElMessage } from 'element-plus';

axios.defaults.baseURL = "http://localhost:8081"

//同一设置
const request = axios.create({
    timeout: 5000,//查询时间
    headers: { //请求头,设置传递参数为json，字符格式为utf-8
        'Content-Type': "application/json; charset=utf-8"
    }
})

//请求拦截,附带请求头
request.interceptors.request.use(config => {
    //拦截请求，覆盖上'Authorization',代表身份
    config.headers['Authorization'] = localStorage.getItem("token")
    return config
})

//根据HTTP状态码，将异常结果返回至前端
request.interceptors.response.use(response => {
        let res = response.data
        if (response.status === 200) {
            return response;
        } else {
            console.log("axios.res");
            console.log(res);
            ElMessage.error(res.msg);
            return Promise.reject(response.data.msg);
        }
    }, error => {

        if (error.response.data) {
            error.message = error.response.data.msg
            console.log(error.response)
            ElMessage.error(error.message);
        }

        if (error.response.status === 401) {
            router.push("/login")
        }

        return Promise.reject(error)

    }
)

export default request